<template>
  <div class="questions-container">
    <el-card>
      <el-row
        type="flex"
        justify="end"
        class="header"
      >
        <el-button
          type="success"
          icon="el-icon-edit"
          size="small"
          @click="$router.push('/questions/new')"
        >新增试题</el-button>
      </el-row>
      <el-form
        ref="form"
        :model="form"
        label-width="90px"
      >
        <!-- 表单 第一行 -->
        <el-row
          type="flex"
          justify="space-between"
        >
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select
                style="width:100%"
                v-model="form.subjectID"
                placeholder="请选择"
                @focus="getSubjectList"
                :loading="subjectListLoading"
                loading-text="正在拼命加载(⊙o⊙)..."
              >
                <el-option
                  v-for="(item,index) in subjectList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select
                style="width:100%"
                v-model="form.catalogID"
                placeholder="请选择"
                :loading="twoLevelListLoading"
                @focus="getTwoLevelList"
                loading-text="正在拼命加载(⊙o⊙)..."
                no-data-text="该学科下无二级目录"
              >
                <el-option
                  v-for="(item,index) in twoLevelList"
                  :key="index"
                  :label="item.directoryName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select
                style="width:100%"
                v-model="form.tags"
                placeholder="请选择"
                :loading="tagsListLoading"
                @focus="getTagsList"
                loading-text="正在拼命加载(⊙o⊙)..."
                no-data-text="该学科下无标签"
              >
                <el-option
                  v-for="(item,index) in tagsList"
                  :key="index"
                  :label="item.tagName"
                  :value="item.tagName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键词">
              <el-input v-model="form.keyword" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 表单 第二行 -->
        <el-row
          type="flex"
          justify="space-between"
        >
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select
                style="width:100%"
                v-model="form.questionType"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item,index) in constants.difficulty"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度">
              <el-select
                style="width:100%"
                v-model="form.difficulty"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item,index) in constants.questionType"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向">
              <el-select
                style="width:100%"
                v-model="form.direction"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item,index) in constants.direction"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select
                style="width:100%"
                v-model="form.creatorID"
                placeholder="请选择"
                :loading="creatorListLoading"
                @focus="getCreatorList"
                loading-text="正在拼命加载(⊙o⊙)..."
              >
                <el-option
                  v-for="(item,index) in creatorList"
                  :key="index"
                  :label="item.username"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 表单 第三行 -->
        <el-row
          type="flex"
          justify="space-between"
        >
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-input v-model="form.remarks" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称">
              <el-input v-model="form.shortName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市">
              <el-row>
                <el-col :span="11">
                  <el-select
                    style="width:100%"
                    v-model="form.city"
                    placeholder="选省份"
                  >
                    <el-option
                      v-for="(item,index) in provinces"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col
                  :span="11"
                  :offset="2"
                >
                  <el-select
                    style="width:100%"
                    v-model="formArea"
                    placeholder="选城市"
                    no-data-text="请先选择省份"
                  >
                    <el-option
                      v-for="(item,index) in area"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item style="display:flex;justify-content: end;">
              <el-button
                size="small"
                @click="purgeFormHandles"
              >清除</el-button>
              <el-button
                type="primary"
                size="small"
                @click="onSubmit"
              >搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <el-alert
        :title="`数据一共${total}条`"
        type="info"
        show-icon
        style="margin-bottom:20px"
      />
      <el-table
        v-loading="loadingShow"
        element-loading-text="试题数据正在加载中..."
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{background:'#fafafa',border:'0px 0px 4px 0px solid #e8e8e8'}"
      >
        <el-table-column
          prop="number"
          label="试题编号"
          width="140"
        />
        <el-table-column
          prop="subject"
          label="学科"
          width="100"
        />
        <el-table-column
          prop="catalog"
          label="目录"
          width="100"
        />
        <el-table-column
          prop="questionType"
          label="题型"
          width="100"
          :formatter="questionTypeFn"
        />
        <el-table-column
          prop="question"
          label="题干"
          width="290"
        >
          <template slot-scope="scope">
            <p v-html='scope.row.question'></p>
          </template>
        </el-table-column>
        <el-table-column
          prop="addDate"
          label="录入时间"
          width="180"
          :formatter="formatterFn"
        />
        <el-table-column
          prop="creator"
          label="录入人"
          width="100"
        />
        <el-table-column
          label="操作"
          width="220"
        >
          <template slot-scope="{row}">
            <el-button
              type="primary"
              icon="el-icon-view"
              plain
              circle
              @click="previewFn(row.id)"
            />
            <el-button
              type="success"
              icon="el-icon-edit"
              circle
              plain
              @click="$router.push({path:'/questions/new',query: {id:row.id}})"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              plain
              @click="delQuestion(row.id)"
            />
            <el-button
              type="warning"
              icon="el-icon-check"
              circle
              plain
              @click="joinChoiceList(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-row
        style="margin-top:25px"
        type="flex"
        justify="end"
      >
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.page"
          :page-sizes="[3, 5, 7, total]"
          :page-size="page.pagesize"
          layout=" prev, pager, next,sizes, jumper"
          :total="total"
        />
      </el-row>
    </el-card>
    <QuestionsPreview
      v-if="questionsPreview"
      :dialogFormVisible.sync="questionsPreview"
      :id="questionsPreviewId"
    />
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys'
import * as constants from '@/api/hmmm/constants'
import { simple as creatorList } from '@/api/base/users'
import { parseTime } from '@/filters/index'
import { simple as subjectList } from '@/api/hmmm/subjects'
import { list as catalogList } from '@/api/hmmm/directorys'
import { list as tagsList } from '@/api/hmmm/tags'
import { list, remove, choiceAdd } from '@/api/hmmm/questions'
import QuestionsPreview from '../components/questions-preview.vue'
export default {
  name: 'Question',
  components: {
    QuestionsPreview
  },
  props: {},
  data () {
    return {
      constants, // 枚举数据
      form: {
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        city: '' // 城市
      },
      formArea: '',
      tableData: [],
      page: {
        page: 1,
        pagesize: 4
      },
      total: null, // 表单数据总数
      loadingShow: false, // 表单加载
      subjectListLoading: false, // 下拉菜单加载
      twoLevelListLoading: false, // 二级列表加载
      tagsListLoading: false, // 标签显示
      creatorListLoading: false, // 录入人列表加载
      subjectList: [], // 学科列表
      twoLevelList: [], // 二级科目列表
      creatorList: [], // 录入人列表
      tagsList: [], // 标签列表
      questionsPreview: false, // 预览显示弹窗
      questionsPreviewId: ''
    }
  },
  // 计算属性
  computed: {
    provinces () {
      return provinces()
    },
    area () {
      return citys(this.form.city)
    }
  },
  // 侦听器
  watch: {
    /**
  * 普通watch无法监听到对象内部属性变化，只有data中数据改变时才能监听变化。因此可添加deep属性:深层遍历，会监听student对象所有属性都变化。
  *
  * **/
    // form: {
    //   handler (newValue, oldValue) {
    //     console.log('"对象所有属性监听"', newValue, oldValue)
    //   },
    //   deep: true
    // }
    // 由于上一种监听每次对象属性变化都会导致handler执行，若只想监听对象中某个属性变化，如下所示
    'form.subjectID': {
      handler (newValue, oldValue) {
        this.form.catalogID = ''
        this.form.tags = ''
      }
    }
  },
  created () {
    // 初始化数据调用getTableList获取表单数据
    this.getTableList()
  },
  mounted () { },
  methods: {
    previewFn (id) {
      // console.log(row)
      this.questionsPreview = true
      this.questionsPreviewId = id
    },
    joinChoiceList (id) {
      this.$confirm('是是否将该课题加入精品课题?', '加入提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingShow = true
        return choiceAdd({ id, choiceState: 1 })
      }).then(() => {
        this.getTableList()
        this.$message({
          type: 'success',
          message: '加入成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消加入'
        })
        this.loadingShow = false
      })
    },
    delQuestion (id) {
      this.$confirm('是是否将该课题删除?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingShow = true
        return remove({ id })
      }).then(() => {
        this.getTableList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
        this.loadingShow = false
      })
    },
    async getTableList () {
      this.loadingShow = true
      const { data } = await list(this.page)
      console.log(data)
      // console.log(dataList)
      this.tableData = data.items
      this.total = data.counts
      this.loadingShow = false
    },
    async onSubmit () {
      this.loadingShow = true
      const newForm = {}
      Object.keys(this.form).forEach(item => {
        if (this.form[item] !== '') {
          newForm[item] = this.form[item]
        }
      })
      console.log(newForm)
      const { data } = await list({ ...this.page, ...newForm })
      console.log(data)
      // console.log(dataList)
      this.tableData = data.items
      this.total = data.counts
      this.loadingShow = false
    },
    // 到分页 单页数据条数发生变化时触发
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.page.pagesize = val
      this.page.page = 1
      this.getTableList()
    },
    // 当 当前所处页数变化时触发
    handleCurrentChange (val) {
      this.page.page = val
      this.getTableList()
    },
    // 表单区域清空操作
    purgeFormHandles () {
      this.form = {
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        city: '' // 城市
      }
    },
    // 格式化表单中的日期
    formatterFn (row, column) {
      // console.log(row, column)
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return parseTime(row[column.property])
    },
    questionTypeFn (row, column) {
      var type = row[column.property]
      if (type === '1') {
        return '单选'
      } else if (type === '2') {
        return '多选'
      } else {
        return '简答'
      }
    },
    // 获取科目列表
    async getSubjectList () {
      this.subjectListLoading = true
      const data = await subjectList()
      console.log(data)
      this.subjectList = data.data
      this.subjectListLoading = false
    },
    // 根据科目获取其二级列表数据
    async getTwoLevelList () {
      this.TwoLevelListLoading = true
      const data = await catalogList({ subjectID: this.form.subjectID })
      this.twoLevelListLoading = false
      console.log(data)
      this.twoLevelList = data.data.items
    },
    // 获取标签列表数据
    async getTagsList () {
      this.tagsListLoading = true
      const data = await tagsList({ subjectID: this.form.subjectID })
      this.tagsListLoading = false
      console.log(data)
      this.tagsList = data.data.items
    },
    // 获取录入人列表数据
    async getCreatorList () {
      this.creatorListLoading = true
      const data = await creatorList()
      this.creatorListLoading = false
      console.log(data)
      this.creatorList = data.data
    }
  }
}
</script>

<style scoped lang="scss">
.questions-container {
  padding: 10px;
  .header {
    margin-bottom: 19px;
  }
}
</style>
